<template>
  <div class="report-form">
    <div class="report-form-content">
      <div class="report-form-content-title">
        <h1 style="font-weight: bold" v-if="oper === 'add'">新增调整单</h1>
        <h1 style="font-weight: bold" v-if="oper === 'edit'">修改调整单</h1>
        <h1 style="font-weight: bold" v-if="oper === 'view'">查看调整单</h1>
      </div>
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" label-width="auto" label-suffix="：" :disabled="oper === 'view'">
        <div style="text-align: right;">
          <div class="tabs-list">
            <el-button type="success" @click="handleSave('obj')">
              <svg-icon icon-class="save" />
              保存
            </el-button>
            <el-button v-show="checkAuthByCode('')" type="primary" @click="handleSubmit('obj')" v-if="obj.id">
              <svg-icon icon-class="submit" />
              提交审批
            </el-button>
          </div>
        </div>
        <div>
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="调整单录入" name="1"></el-tab-pane>
            <el-tab-pane label="经济支出预算" name="2" v-if="expenditureKpiObj.isEconomic === '1'"></el-tab-pane>
          </el-tabs>
          <div class="tabs-list" v-show="activeName === '1'">
            <el-row :gutter="20">
              <el-col :sm="24" :lg="24" style="padding-left: 20px">
                <el-card class="update-log">
                  <div class="report-form-list-content">
                    <el-form-item label="指标编码">
                      <span>{{ expenditureKpiObj.kpiCode }}</span>
                    </el-form-item>
                    <el-form-item label="指标名称">
                      <span>{{ expenditureKpiObj.kpiName }}</span>
                    </el-form-item>
                    <el-form-item label="可用金额">
                      <span v-if="expenditureKpiObj.kpiCode">￥{{ expenditureKpiObj.availableAmount }}</span>
                    </el-form-item>
                  </div>
                  <div class="report-form-list-content">
                    <el-form-item prop="expenditureKpiId">
                      <el-button type="primary" icon="search" @click="chooseExpenditureKpi">选择指标单</el-button>
                    </el-form-item>
                    <el-button :disabled="!expenditureKpiObj.id" style="margin-left: 16px" @click="expenditureKpiDrawer = true">
                      <svg-icon icon-class="view" />查看详情
                    </el-button>
                    <el-drawer v-model="expenditureKpiDrawer" title="指标单详情">
                      <div class="report-form-list-content report-form-list-content-be">
                        <el-form label-suffix="：">
                          <el-form-item label="预算年度">
                            <span>{{ expenditureKpiObj.year }}</span>
                          </el-form-item>
                          <el-form-item label="支出类型">
                            <span>
                              <DictTag :dict-list="getDictList('ExpenditureKpiPayType')" :dict-key="expenditureKpiObj.payType" />
                            </span>
                          </el-form-item>
                          <el-form-item label="经费类型">
                            <span>
                              <DictTag :dict-list="getDictList('ExpenditureKpiFundType')" :dict-key="expenditureKpiObj.fundType" />
                            </span>
                          </el-form-item>
                          <el-form-item label="预算总金额">
                            <MoneyTag :money="expenditureKpiObj.amount" />
                          </el-form-item>
                          <el-form-item label="可用金额">
                            <MoneyTag :money="expenditureKpiObj.availableAmount" />
                          </el-form-item>
                          <el-form-item label="项目负责人部门">
                            <span><LabelTag :foreignList="organizationList" :foreignIds="expenditureKpiObj.organizationId" :foreignLabel="'organizationName'" /></span>
                          </el-form-item>
                          <el-form-item label="项目负责人">
                            <span><LabelTag :foreignList="userList" :foreignIds="expenditureKpiObj.managerId" :foreignLabel="'name'" /></span>
                          </el-form-item>
                          <el-form-item label="功能分类">
                            <span>{{ showIdLabel(expenditureFunctionalList, expenditureKpiObj.expenditureFunctionalId, 'name') }}</span>
                          </el-form-item>
                          <el-form-item label="财政项目">
                            <span>{{ showIdLabel(expenditureFiscalList, expenditureKpiObj.expenditureFiscalId, 'name') }}</span>
                          </el-form-item>
                          <el-form-item label="指标来源">
                            <span>
                              <DictTag :dict-list="getDictList('ExpenditureKpiSource')" :dict-key="expenditureKpiObj.source" />
                            </span>
                          </el-form-item>
                          <el-form-item label="项目类型">
                            <span>{{ showIdLabel(expenditurePtypeList, expenditureKpiObj.expenditurePtypeId, 'name') }}</span>
                          </el-form-item>
                          <el-form-item label="指标单状态">
                            <span>
                              <EnumTag :enum-list="getEnumList('ExpenditureKpiState')" :enum-key="expenditureKpiObj.state" />
                            </span>
                          </el-form-item>
                          <el-form-item label="按经济分类控制金额">
                            <span>
                              <EnumTag :enum-list="getEnumList('CommonYesNo')" :enum-key="expenditureKpiObj.isEconomic" />
                            </span>
                          </el-form-item>
                        </el-form>
                      </div>
                    </el-drawer>
                  </div>
                </el-card>
              </el-col>
              <el-col :sm="24" :lg="24" style="padding-left: 20px">
                <el-card class="update-log">
                  <div class="report-form-list-content">
                    <el-form-item label="调整单号" prop="adjustmentCode">
                      <el-input v-model="obj.adjustmentCode" placeholder="自动生成" disabled />
                    </el-form-item>
                    <el-form-item label="填单人部门" prop="submitOrganizationId">
                      <Organization v-model="obj.submitOrganizationId" keyName="id" keyShow="organizationName" placeholder="填单人部门" title="部门查询" />
                    </el-form-item>
                    <el-form-item label="填单人用户" prop="submitUserId">
                      <User v-model="obj.submitUserId" keyName="id" keyShow="name" placeholder="填单人用户" title="用户查询" />
                    </el-form-item>
                    <el-form-item label="调整日期" prop="adjustmentDate">
                      <el-date-picker v-model="obj.adjustmentDate" placeholder="请输入调整日期" type="date" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="调整前金额">
                      <el-input-number v-model="obj.beforeAmount" placeholder="请输入调整前金额" :precision="2" disabled />
                    </el-form-item>
                    <el-form-item label="调整金额" prop="adjustAmount">
                      <el-input-number v-model="obj.adjustAmount"
                                       placeholder="请输入调整金额"
                                       @change="changeAdjustAmount"
                                       :precision="2" :disabled="expenditureKpiObj?.isEconomic === '1'" />
                    </el-form-item>
                    <el-form-item label="调整后金额" prop="afterAmount">
                      <el-input-number v-model="obj.afterAmount" placeholder="请输入调整后金额" :precision="2" disabled />
                    </el-form-item>
                    <el-form-item label="调整比例">
                      <el-input-number v-model="obj.adjustRate" placeholder="调整比例" :precision="0" disabled />%
                    </el-form-item>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            <el-divider />
          </div>
          <div class="tabs-list" v-show="activeName === '2'">
            <div class="" style="display: flex;align-items: center;justify-content: space-between;">
              <div style="font-weight: bold; color: brown;">合计调整金额：￥{{ totalAdjustAmount }}</div>
            </div>
            <el-divider />
            <div class="report-form-list-content" v-for="(item,index) in items" :key="index">
              <label class="form-label">经济分类信息{{ index + 1 }}:</label>
              <el-card class="update-log update-log-1">
                <div class="report-form-list-content">
                  <el-form-item label="经济分类">
                    <el-cascader v-model="item.expenditureEconomicId" :options="arrChangeTreeFn(expenditureEconomicList)" :props="{label: 'name', value: 'id'}" :show-all-levels="false" disabled />
                  </el-form-item>
                  <el-form-item label="调整前金额">
                    <el-input-number v-model="item.beforeAmount" placeholder="请输入调整前金额" :precision="2" disabled />
                  </el-form-item>
                  <el-form-item label="调整金额">
                    <el-input-number v-model="item.adjustAmount" placeholder="请输入调整金额" @change="changeItemAdjustAmount(item)" :precision="2" />
                  </el-form-item>
                  <el-form-item label="调整后金额">
                    <el-input-number v-model="item.afterAmount" placeholder="请输入调整后金额" :precision="2" disabled />
                  </el-form-item>
                  <el-form-item label="调整比例">
                    <el-input-number v-model="item.adjustRate" placeholder="调整比例" :precision="0" disabled />%
                  </el-form-item>
                  <el-form-item label="浮动率">
                    <el-input-number v-model="item.fluctuate" placeholder="请输入浮动率" :min="0" :precision="0" />%
                  </el-form-item>
                </div>
                <div class="report-form-list-content-1">
                  <el-form-item label="备注">
                    <el-input v-model="item.remark" :autosize="{ minRows: 2, maxRows: 5}" type="textarea" class="textarea-1" />
                  </el-form-item>
                </div>
              </el-card>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <selectExpenditureKpiList v-model:itemsVisible="itemsVisible" @close="itemsVisible = false" @expenditureKpiSelect="changeExpenditureKpi"></selectExpenditureKpiList>
    <selectApprove v-model:itemsVisible="dialogApproveVisible" @close="dialogApproveVisible = false" :business="'2003'" :businessId="obj.id" @doSubmit="doSubmit" />
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost} from '@/config/http'
import {alertErrorMsg, arrChangeTreeFn, customValidator, getListPageSize, notifySuccess, showIdLabel} from '@/config/common'
import selectExpenditureKpiList from '@/views/components/expenditure/selectExpenditureKpiList.vue'
import selectApprove from "@/views/components/base/selectApprove.vue";
import {parseTime} from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import SvgIcon from "@/components/SvgIcon/index.vue";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  approveId: null,
  expenditureKpiId: null, // 指标单表ID
  adjustmentCode: null, // 调整单号
  submitOrganizationId: useUserStore().organization.id, // 填单人部门ID
  submitUserId: getUserId(), // 填单人用户ID
  adjustmentDate: parseTime(new Date().getTime(), '{y}-{m}-{d}'), // 调整日期
  beforeAmount: 0, // 调整前金额
  adjustAmount: 0, // 调整金额
  afterAmount: 0, // 调整后金额
  adjustRate: 0, // 调整比例
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

const emptyItem = {
  expenditureAdjustmentId: null, // 调整单表ID
  expenditureEconomicId: null, // 经济分类ID
  beforeAmount: 0, // 调整前金额
  adjustAmount: 0, // 调整金额
  afterAmount: 0, // 调整后金额
  adjustRate: 0, // 调整比例
  fluctuate: 0, // 浮动率
  remark: null, // 备注
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'expenditureAdjustmentEdit_nocache',
  mixins: [baseConfig],
  components: {
    Organization,
    User,
    SvgIcon,
    selectApprove,
    selectExpenditureKpiList,
  },
  data() {
    return {
      svc: 'icims-api',
      obj: Object.assign({}, emptyObj),
      routes: [],
      oper: null,
      id: null,
      activeName: '1',
      items: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      itemsVisible: false,
      dialogApproveVisible: false,
      rules: {
        expenditureKpiId: [{ required: true, validator: customValidator, min: 1, max: 100, label: '指标单', trigger: ['blur', 'change'] }],
        adjustmentCode: [{ required: false, validator: customValidator, min: 0, max: 200, label: '调整单号', trigger: ['blur', 'change'] }],
        submitOrganizationId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '填单人部门ID', trigger: ['blur', 'change'] }],
        submitUserId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '填单人用户ID', trigger: ['blur', 'change'] }],
        adjustmentDate: [{ required: true, validator: customValidator, min: 0, max: 100, label: '调整日期', trigger: ['blur', 'change'] }],
        adjustAmount: [{ required: true, validator: customValidator, min: 0, max: 13, label: '调整金额', trigger: ['blur', 'change'] }],
        afterAmount: [{ required: false, validator: customValidator, min: 0, max: 13, label: '调整后金额', trigger: ['blur', 'change'] }],
        adjustRate: [{ required: false, validator: customValidator, min: 0, max: 13, label: '调整比例', trigger: ['blur', 'change'] }],
      },
      governmentList: initListStore().governmentList,
      organizationList: initListStore().organizationList,
      userList: initListStore().userList,
      expenditurePtypeList: initListStore().expenditurePtypeList,//项目类型
      expenditureFunctionalList: initListStore().expenditureFunctionalList,//功能分类
      expenditureEconomicList:initListStore().expenditureEconomicList,//经济分类
      expenditureFiscalList: initListStore().expenditureFiscalList,//财政项目
      expenditureSubjectList: initListStore().expenditureSubjectList,//会计科目
      expenditureKpiObj: {
        kpiCode: null, // 指标编码
        kpiName: null, // 指标名称
        kpiDate: null, // 单据日期
        year: null, // 预算年度
        payType: null, // 支出类型
        fundType: null, // 经费类型
        amount: null, // 预算总金额
        organizationId: null, // 项目负责人部门ID
        managerId: null, // 项目负责人
        expenditurePtypeId: null, // 项目类型ID
        expenditureFunctionalId: null, // 功能分类ID
        expenditureFiscalId: null, // 财政项目ID
        source: null, // 指标来源
        state: null, // 状态
        isEconomic: null, // 按经济分类控制金额
      },
      expenditureKpiDrawer: false,
      approveList: [], // 审批模板列表
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
    totalAdjustAmount() {
      let total = 0
      this.items.forEach(item => total += parseFloat(item.adjustAmount))
      this.obj.adjustAmount = total
      this.changeAdjustAmount()
      return total
    },
  },
  created() {
    this.initObj()
    // this.initList()
  },
  methods: {
    showIdLabel,
    arrChangeTreeFn,
    // async initList() {
    //   let p1 = doGet(this.svc, '/government/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(this.svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p4 = doGet(this.svc, '/expenditure-ptype/page', {pageSize: getListPageSize()}, false)
    //   let p5 = doGet(this.svc, '/expenditure-functional/page', {pageSize: getListPageSize()}, false)
    //   let p6 = doGet(this.svc, '/expenditure-economic/page', {pageSize: getListPageSize()}, false)
    //   let p7 = doGet(this.svc, '/expenditure-fiscal/page', {pageSize: getListPageSize()}, false)
    //   let p8 = doGet(this.svc, '/expenditure-subject/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8])
    //   this.governmentList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.userList = resArray[2]['records']
    //   this.expenditurePtypeList = resArray[3]['records']
    //   this.expenditureFunctionalList = resArray[4]['records']
    //   this.expenditureEconomicList = resArray[5]['records']
    //   this.expenditureFiscalList = resArray[6]['records']
    //   this.expenditureSubjectList = resArray[7]['records']
    // },
    async initObj() {
      this.oper = this.$route.query.oper
      this.id = null
      if (this.$route.query.id) {
        this.id = this.$route.query.id
        this.obj = await doGet(this.svc, '/expenditure-adjustment/' + this.id, {}, true)
        this.items = await doGet(this.svc, '/expenditure-adjustment-item/listByField', {field: 'expenditureAdjustmentId', values: this.id}, false)
        this.items.map(item => item.expenditureEconomicId = item.expenditureEconomicId?.split(','))
        if (this.obj.expenditureKpiId) {
          this.expenditureKpiObj = await doGet(this.svc, '/expenditure-kpi/' + this.obj.expenditureKpiId, {}, false)
        }
      }
    },
    chooseExpenditureKpi() {
      this.itemsVisible = true
    },
    changeExpenditureKpi(data) {
      this.expenditureKpiObj = data
      this.obj.expenditureKpiId = data.id
      this.obj.beforeAmount = data.amount
      this.obj.afterAmount = this.obj.beforeAmount + this.obj.adjustAmount
      this.items = []
      doGet(this.svc, '/expenditure-kpi-item/listByField', {field: 'expenditureKpiId', values: this.obj.expenditureKpiId}, false).then(res => {
        if (res.length > 0) {
          res.map(item => {
            let o = {
              expenditureEconomicId: item.expenditureEconomicId?.split(','),
              beforeAmount: item.amount,
              fluctuate: item.fluctuate,
              adjustAmount: 0,
              afterAmount: 0,
              adjustRate: 0,
            }
            o.afterAmount = o.beforeAmount + o.adjustAmount
            this.items.push(o)
          })
        }
      })
    },
    changeAdjustAmount() {
      this.obj.afterAmount = this.obj.beforeAmount + this.obj.adjustAmount
      this.obj.adjustRate = parseInt(((this.obj.afterAmount - this.obj.beforeAmount) * 100 / this.obj.beforeAmount).toFixed(0))
    },
    changeItemAdjustAmount(item) {
      item.afterAmount = item.beforeAmount + item.adjustAmount
      item.adjustRate = parseInt(((item.afterAmount - item.beforeAmount) * 100 / item.beforeAmount).toFixed(0))
    },
    async handleSave(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let o = this.buildObj()
      doPost(this.svc, '/customExpenditureKpis/saveExpenditureAdjustment', o, true).then(() => {
        notifySuccess('保存成功')
        this.goTargetByName('expenditureAdjustment', {}, true)
        this.dialogViewVisible = false
      })
    },
    async handleSubmit(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let o = this.buildObj()
      doPost(this.svc, '/customExpenditureKpis/saveExpenditureAdjustment', o, false).then(res => {
        this.obj.id = res['id']
        this.obj.version = res['version']
        this.items.map(item => item.expenditureEconomicId = item.expenditureEconomicId?.split(','))
        this.dialogApproveVisible = true
      })
    },
    async doSubmit(data) {
      const formName = 'obj'
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let o = this.buildObj()
      o.approveId = data.approveId
      o.approveNodes = data.approveNodes
      doPost(this.svc, '/customExpenditureKpis/submitExpenditureAdjustment', o).then(() => {
        notifySuccess('操作成功')
        this.goTargetByName('expenditureAdjustment', {}, true)
        this.dialogViewVisible = false
      })
    },
    buildObj() {
      let o = this.obj
      //items
      o.items = []
      o.items = this.items.map(item => {
        if (item.itemType && typeof(item.itemType) === 'object' && item.itemType.length > 0) {
          item.itemType = item.itemType[1]
        }
        item.expenditureEconomicId = item.expenditureEconomicId instanceof Array ? item.expenditureEconomicId.join(',') : item.expenditureEconomicId
        return item
      })
      return o
    },
    // 新增行
    addItem() {
      let item = Object.assign({}, emptyItem)
      this.items.push(item)
    },
    // 删除行
    removeItem(index) {
      this.items.splice(index, 1)
    },
  }
}
</script>
<style scoped>
.report-form {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: #fff;
  z-index: 10;
  padding: 20px;
  overflow-x: hidden;
  overflow-y: auto;
}
.report-form-content-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.form-label {
  display: inline-flex;
  justify-content: flex-end;
  align-items: flex-start;
  flex: 0 0 auto;
  font-size: 16px;
  color: #337ecc;
  height: 32px;
  line-height: 32px;
  padding: 0 12px 0 0;
  box-sizing: border-box;
  width: 200px;
  font-weight: bold;
}
.update-log {
  width: 100%;
  margin: 30px 0;
}
.update-log-1 {
  margin-top: 0;
}
</style>
